$.fn.eUpload = function(options) {
    return this.each(function() {
        const eupload =  new EUpload(this, options)
        $(this).data('eupload', eupload)
    })
}



function EUpload(el, options) {
    this.$el = $(el)
    this.options = options
    this.init()
}

EUpload.prototype = {
    init: function() {
        this.build()
        this.initEvent()
    },
    build: function() {
        const htmls = [
            '<div class="eUpload">',
                '<div class="eUpload-dragger">',
                    '<div class="eUpload-dragger-txt">',
                        '<i class="fa fa-cloud-upload"></i>',
                        '<div class="eUpload-tip">点击或拖拽上传</div>',
                    '</div>',
                    '<div class="eUpload-dragger-name" style="display: none;">',
                        '<div class="eUpload-dragger-info"></div>',
                        '<i class="eUpload-dragger-close fa fa-close"></i>',
                    '</div>',
                '</div>',
                '<input type="file" class="eUpload-file"/>',
            '</div>'
        ]
        this.$el.css({width: '100%', height: '100%'})
        this.$el.html(htmls.join(''))
    },
    initEvent: function() {
        const _this = this
        const $txt = this.$el.find('.eUpload-dragger-txt')
        const $name = this.$el.find('.eUpload-dragger-name')
        const file = this.$el.find('.eUpload-file')[0]
        const dragel = this.$el.find('.eUpload-dragger')[0]
        const $close = this.$el.find('.eUpload-dragger-close')

        $txt.on('click', function() {
            file.click()
        })
        file.addEventListener('change', function(e) {
            dealFile(e.target.files[0])
        })

        dragel.addEventListener('dragenter', handleEvent)
        dragel.addEventListener('dragover', handleEvent)
        dragel.addEventListener('drop', handleEvent)
        dragel.addEventListener('dragleave', handleEvent)

        $close.on('click', function() {
            $name.hide()
            $txt.show();
            file.value = ''
            _this.file = null
        })

        function handleEvent(e) {
            e.preventDefault()
            if(e.type === 'dragover') {
                dragel.style.borderColor = 'var(--color)'
            } else if(e.type === 'dragleave') {
                dragel.style.borderColor = 'currentColor'
            } else if(e.type === 'drop') {
                dealFile(e.dataTransfer.files[0])
            }
        }

        function dealFile(file) {
            $name.find('.eUpload-dragger-info').html(file.name)
            $name.show()
            $txt.hide()
            _this.file = file
        }
    },
    clear: function() {
        this.$el.find('.eUpload-dragger-close').trigger('click')
    },
    getFile: function() {
        return this.file
    }
}